<?php defined('SYSPATH') or die('No direct script access.');

	class Model_Services_Analysis extends Model implements Jqgrid_GridListener{
		
		public $analysis = NULL;
		
		public function __construct($id=false){
			if ($id) $this->analysis = $this->get($id);
		}

		//public functio
	
		public function count($criteria = false){
			return ORM::factory("dao_analysis")->count_all();
		}
				
		public function getList($criteria = false){
			
			if (!$criteria)	$analysis_list = ORM::factory("dao_analysis")->find_all()->as_array();
			else{
				
				if ($criteria->isSearch){
					
					if ($criteria->searchField == 'doctype'){
						$criteria->searchField = 'id';
						$tablename = "patient.doctype_id";
					}else{
						$tablename = $criteria->getSQLField("patient");
					}
					
					if ($criteria->searchField == "analysis_date"){
						$criteria->searchString = Helper_Date::dateToMysql($criteria->searchString);
						$tablename = "analysis";
					}
					
					$analysis_list = ORM::factory("dao_analysis")
									->with('patient')
									->with('doctype')
									->where($tablename, $criteria->getSQLOper(), $criteria->getSQLSearchString())
									->order_by($criteria->sidx,$criteria->sord)
									->limit($criteria->limit)
									->offset($criteria->calcOffset())
									->find_all()
									->as_array();
							
				}else{
					$analysis_list = ORM::factory("dao_analysis")->order_by($criteria->sidx,$criteria->sord)->limit($criteria->limit)->offset($criteria->calcOffset())->find_all()->as_array(); 
				}
				
				
				
			} 
		
			$dataset = array();
			foreach ($analysis_list as $analysis){
				$dataset[$analysis->id] = array(
												Helper_Date::mysqlToDate($analysis->analysis_date),
												$analysis->patient->surname,
												$analysis->patient->name,
												$analysis->patient->doctype->description,
												$analysis->patient->identity_card_number);
			}
			
			return $dataset;
		}
		
		/**
		*
		* get analysis from an id
		* @param int $minId
		* @param int $maxAmount
		* @return array of analysis
		*/
		public function getListFromMinID($minId, $maxAmount){
			return ORM::factory("dao_analysis")->where("id",">",$minId)->order_by("id", "ASC")->limit($maxAmount)->find_all()->as_array();
		}
		
		
		public function get($id){
			return ORM::factory("dao_analysis")->find($id);
		}
		
		
		public function includeInStats($id_analysis, $include_in = true){
			$this->analysis = ORM::factory("dao_analysis",$id_analysis);
			$this->analysis->include_in_stats = ($include_in) ? 1 : 0;
			$this->analysis->save();
		}
		
		
		public function save($id, array $data){
			
			$this->analysis = ($id > 0) ? ORM::factory("dao_analysis",$id) : ORM::factory("dao_analysis");
			$this->analysis->patient_id = $data["patient_id"];
			$this->analysis->medic_id = $data["medic_id"];
			$this->analysis->creation_date = $data["creation_date"];
			$this->analysis->analysis_date = $data["analysis_date"];
			$this->analysis->file_name = $data["file_name"];
			$this->analysis->raw_signal_id = $data["raw_signal_id"];
			$this->analysis->analysis_result_id = $data["analysis_result_id"];
			$this->analysis->report_id = $data["report_id"];
			$this->analysis->final_segment_id = $data["final_segment_id"];
			$this->analysis->period_id = $data["period_id"];				
			$this->analysis->clinical_info_id = $data["clinical_info_id"];	

			$this->analysis->save();			
        	return $this->analysis->id;    	
    	}
		
		public function delete($id){
			
		}
		
		
		public function getClinicalData(){
			if ($this->analysis) return Helper_Service::factory("clinicalinformation",$this->analysis->clinical_info_id);
			return NULL;
		}
		
		public function getFinalSegment(){
			if ($this->analysis) return Helper_Service::factory("finalsegment",$this->analysis->final_segment_id)->getFinalSegment();
			return NULL;
		}
		
		public function getMedic(){
			if ($this->analysis) return Helper_Service::factory("medic",$this->analysis->medic_id);
			return NULL;
		}
		
		public function getPatient(){
			if ($this->analysis) return Helper_Service::factory("patient",$this->analysis->patient_id);
			return NULL;
		}
		
		public function getPeriod(){
			if ($this->analysis) return Helper_Service::factory("samplingperiod")->get($this->analysis->period_id);
			return NULL;
		}
		
		public function getRawSignal(){
			//if ($this->analysis) return $this->analysis->raw_signal->find();
			if ($this->analysis) return Helper_Service::factory("rawsignal",$this->analysis->raw_signal_id);
			return NULL;
		}
		
		public function getReport(){
			if ($this->analysis) return Helper_Service::factory("report",$this->analysis->report_id);
			return NULL;
		}
			
		public function getResults(){
			if ($this->analysis) return Helper_Service::factory("analysisresult",$this->analysis->analysis_result_id);
			return NULL;
		}
		
		public function getSelectedSegments(){
			if ($this->analysis) return Helper_Service::factory("selectedsegment",$this->analysis->id);
			return NULL;
		}
		

		public function export(){
			$patient = $this->getPatient();
			$analysis_date = Helper_Date::mysqlToDate($this->analysis->analysis_date);

			$dataExporter = new Model_AnalysisDataExporter(str_replace(" ", "", $patient->getSurname())."_".str_replace(" ", "", $patient->getName()),$analysis_date);
			$dataExporter->addFinalSegment($this->getFinalSegment());
			$dataExporter->addRawSignal($this->getRawSignal()->getSamples());
			$dataExporter->addResults($this->getResults());
			
			$selected_segment_list = array();
			$selected_segment_service = $this->getSelectedSegments();
			$daoSegmentList = $selected_segment_service->selected_segments; 
			foreach($daoSegmentList as $daoSegment){
				array_push($selected_segment_list,array(
														"number"=>$daoSegment->number,
														"segment"=>$selected_segment_service->getSegmentData($daoSegment->segment)
														));
			}
			$dataExporter->addSelectedSegments($selected_segment_list);
			
			if ($clinicalInfo = $this->getClinicalData()){
				$dataExporter->addClinicalInformation($clinicalInfo);
			}
			
			$dataExporter->export();
		}
		
	}


